package ck

import (
	"gitee.com/tietang/terrace-go/v2/example/moni/dao"
	"gitee.com/tietang/terrace-go/v2/lib/rpc"
	"github.com/sirupsen/logrus"
	"github.com/tietang/dbx"
)

var ckWebSlowDao = new(ClickHouseWebSlowDao)

func init() {
	//dao.Register("slow.SlowMetrics", ckWebSlowDao)
	handler := dao.NewHandler(ckWebSlowDao)
	rpc.RegisterHandler("slow.SlowMetrics", handler)
}

type ClickHouseWebSlowDao struct {
}

func (d *ClickHouseWebSlowDao) Save(metrics any) {
	met := metrics.(map[string]interface{})

	args := make([]interface{}, 0, 12)

	args = append(args, met["appName"])
	args = append(args, met["hostName"])
	args = append(args, met["uri"])
	args = append(args, met["httpMethod"])
	args = append(args, met["millis"])
	args = append(args, met["cost"])
	args = append(args, met["count"])
	args = append(args, met["failure40xCount"])
	args = append(args, met["failure50xCount"])
	args = append(args, met["bizErrorCount"])
	args = append(args, met["requestByteSize"])
	args = append(args, met["responseByteSize"])

	Clickhouse().Tx(func(run *dbx.TxRunner) error {
		_, err := run.Exec(SqlSlowRequest, args...)
		if err != nil {
			logrus.Error(err)
			return err
		}
		return nil
	})

}

func (d *ClickHouseWebSlowDao) Init() {

	Clickhouse().Tx(func(run *dbx.TxRunner) error {
		run.Exec(WebSlowCreateTable)
		return nil
	})
}

const SqlSlowRequest = "INSERT INTO m_slow_request ( app_name,hostname,uri,http_method, ts,cost,ct,err_40xct,err_50xct,berr_ct,req_size,res_size) " +
	//cost,count,failureCount,failure40xCount,failure50xCount,errorCount,bizErrorCount, requestByteSize, responseByteSize
	//"from input (' app_name String,  hostname String,  uri String, http_method String,   ts UInt64, cost Int64, ct Int64,  err_40xct Int64, err_50xct Int64,   berr_ct Int64, req_size Int64, res_size Int64')"
	"values (?,?,?,?,?,?,?,?,?,?,?,?)"

const WebSlowCreateTable = "create table if not exists m_slow_request" +
	" (" +
	" app_name String," +
	" hostname String," +
	" uri String," +
	" http_method String," +
	" ts UInt64," +
	" cost Int64," +
	" ct Int64," +
	" err_40xct Int64," +
	" err_50xct Int64," +
	" berr_ct Int64," +
	" req_size Int64," +
	" res_size Int64," +
	" d Date materialized toDate(round(ts / 1000))," +
	" dt DateTime materialized toDateTime(round(ts / 1000))" +
	" ) " +
	" engine = MergeTree PARTITION BY (toYYYYMM(dt), app_name)\n" +
	"        ORDER BY dt\n" +
	"        SETTINGS index_granularity = 8192;"
